﻿var sword = window.sword || {};
sword.ajax  = function(options) {
	   var defaultoptions = {
			url : null,  //请求URL
			method:"post", //提交方式
			async:false,
			data:'', //发送的数据
			onSuccess : $empty, //成功请求后的处理函数
			onFailure : $empty  //请求失败后的处理函数
	  };
	  var newoptions = $extend(defaultoptions,options); 
	  new Request(newoptions).send(newoptions.data);
};
var $cache=sword.CacheManager = { 
	 batchget:function(paramlist,fn){	
		 //定义数组，存放由SQL中截取出来的缓存表名称
		//定义数组 ，存放所有需要后台请求缓存表数据的缓存表名称（可能本地版本低或者没有被缓存过等等）
		 	var  requestarr = [];
		 	//返回回调函数的HASH ，KEY为缓存表名称，VALUE为已经处理的缓存表数据
		 	var returnhash = $H();		 
		 	var curObj = "";
		 	var sql="";
		 var keys = paramlist.getKeys();
		 keys.each(function(tname){
			 var sql = paramlist.get(tname);
				$cache.initCacheContainer(tname);
				curObj = $cache.curCacheObj;
				if(curObj){
					curObj.get(tname+"_version",function(ok,version,key){
					if (ok){//get version success
						if($chk(version)){
							var v = curObj.getServerCache(key);
							if($chk(v)){
								  if(parseInt(version) != parseInt(v)){/*版本过低*/
									     requestarr.push(key);
								   }else{/*版本一致 ，从缓存中加载数据*/
									   var cData = pc.getTopCacheData(tname);
									   if(!cData){
										   curObj.get(key,function(ok,val){		
												if(ok){ 
													var dObj = JSON.decode(val);
						              				var cObj = $H({"data":[{"data":dObj,cache:tname}]});
						              				if(!top.pc.cacheData){
						              					top.pc.cacheData = cObj; 
						              				}else top.pc.cacheData.data.extend(cObj.data);
						              				
													val = $cache.query(dObj,sql,key);	
													returnhash.set(key,val);
													
												}else{													
													requestarr.push(key);
												}
											});
									   }else {
										   val = $cache.query(cData.data,sql,key);	
											returnhash.set(key,val);
									   }
								   }
							}else{					
								 requestarr.push(key);
							}
						}
					}else{
						requestarr.push(key);
					}
				});
			}	
		 });
			/*如果requestarr数组中有数据，则代表需要请求后台缓存表*/
			if (requestarr.length !=0){
					sword.ajax({
			 			url : "ajax.sword?FromSwordLoading=true&ctrl=CacheCtrl_batchGetCacheData&sName=CacheCtrl_batchGetCacheData",             
		              	data:"tableNameList="+requestarr.join("#"),                  
		              	onSuccess : function(res){
						var resJson = JSON.decode(res);
						if (resJson['exception']) {
						 if(resJson['ajaxErrorPage']) {
			                    if(!resJson['exceptionMes'])resJson['exceptionMes']='';
			                    var popupParam = JSON.decode(resJson['ajaxErrorPopupParam'].replace(/&apos;/g, "'")) || {titleName:'出错了！',width: 412,height:450};
			                    var doctemp=window.document;
			                    var scrollTop=0;
			                    if (doctemp.body && doctemp.body.scrollTop)
			                    {
			                    	scrollTop=doctemp.body.scrollTop;
			                    }else if (doctemp.documentElement && doctemp.documentElement.scrollTop)
			                    {
			                    	scrollTop=doctemp.documentElement.scrollTop;
			                    }
			                    popupParam['top'] = popupParam.top + scrollTop;
			                    popupParam['param'] = {'win':window,'data':resJson};
			                    swordAlertIframe(jsR.rootPath + 'sword?ctrl=SwordPage_redirect&pagename=' + resJson['ajaxErrorPage'], popupParam,null);
			                }  else {
			                    this.alertError('<b><font color="red">出错了！</font></b>' +
			                            '<br><font color="blue" >错误名称</font> : ' + resJson['exceptionName']
			                            + '  <br><font color="blue" >错误信息</font> : ' + resJson['exceptionMes']
			                            + '<br><font color="blue" >调试信息</font> : ' + resJson['debugMes']);
			                    }
						}else{
							 resJson.data.each(function(item){
			              			var temp = item.name.split("^");
			              			var tableName = temp[0];
			              			var version = temp[1];		              		 
			              			if (curObj){
			              				var result = curObj.uncompress(item.value);	
			              				curObj.set(tableName,result);
			              				var dObj = JSON.decode(result);
			              				var cObj = $H({"data":[{"data":dObj,cache:tableName}]});
			              				if(!top.pc.cacheData){
			              					top.pc.cacheData = cObj; 
			              				}else top.pc.cacheData.data.extend(cObj.data);
			              				returnhash.set(tableName,$cache.query(dObj,sql,tableName));	
			              				curObj.set(tableName+"_version",version);
			              			}		              		 
			              		});
						}
		              	}
				   });
			}		
			//回调函数
			fn.call(this,returnhash);
	 },
	
	/**
		初始化缓存容器
	*/
	initCacheContainer:function(tableName){
		/*从顶层获取缓存对象*/
		if (this.curCacheObj == null){			 
			this.curCacheObj = top.$swfcacheobject;
		}
	},
	//解压缩数据
	uncompress:function(data){
		return this.curCacheObj.uncompress(data);
	},
	//根据sql查询缓存数据
	query:function(data,sql,tableName){
	     if($chk(sql)){
	    	 var schema = $H();
			 var schemaVal = $H();
			 var  filterData  = $H();
	    	 if(data.length > 0 ){
		    	 tempHash = $H(data[0]);
		    	 var keys = tempHash.getKeys();
		     
		         keys.each(function(item,index){
		    	 schemaVal.set(item,{type:"String"});
		     });}
		     schema.set(tableName,schemaVal);
		     filterData.set(tableName,data);
			 var results = TrimPath.makeQueryLang(schema).parseSQL(sql).filter(filterData);
			 return results;
	     }else return data;
    },
	//自定义缓存调用接口
	getswordcacheInstance:function(){
    	if(this.swordcacheInstance==null){
	    	this.swordcacheInstance = Persist();
	    	var options = {
    				url : "ajax.sword?ctrl=CacheCtrl_getAllVersion",  
    				async:false,
    				method:"post", //提交方式
    				data:'', //发送的数据
    	          	onSuccess : function(res) {
    	          		JSON.decode(res).data.each(function(el){
    	          			top.servercache.set(el.name,el.value);
    					});
    					isCache = true;
    				},
    	          	onFailure : function() {
    					alert('获取服务器缓存代码表信息出错！');
    				}
    		  };
        	 new Request(options).send(options.data);
    	}
    	return this.swordcacheInstance;
    },
    getDataByKey:function(key,sql){
    	var data = null;
    	top.$swfcacheobject.get(key,function(ok,val){		
				if(ok){ 
			    	if($chk(sql)){
			    		data = $cache.query(val,sql,key);
			    	}else data = JSON.decode(val);
				}
			});
    	return data;
    },
    setDataByKey:function(table, fn, scope){
    	var allData = this.getDataByKey(table);
    	var insertArr = new Array();
    	 if (fn){
    		 insertArr = fn.call(scope || this,allData);
    	 }
    	if($chk(allData)){
    		allData.extend(insertArr);
    	}else allData = insertArr;
    	
    	top.$swfcacheobject.set(table,JSON.encode(allData));
    }
};